package io.afu.validator.Implement;

import io.afu.validator.Annimation.ChineseWord;
import io.afu.validator.Annimation.NotEmptyIfParamIs;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Field;

public class NotEmptyIfParamIsImpl implements ConstraintValidator<NotEmptyIfParamIs,Object> {


    private String targetElement;

    private String moniteElement;

    private String elementValue;


    @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
        Class cls = o.getClass();
        boolean verify = true;
        Field[] fields = cls.getDeclaredFields();
        for (Field field:fields){
            try {
            field.setAccessible(true);
            String name = field.getName();
            Class eleType = field.getType();
            if (eleType.isInstance(String.class)){
                    String value = (String) field.get(o);
                    if (value!= null && !value.equals("")){
                        verify = true;
                    }
            }else {
                Object v = field.get(o);
                if (v != null){
                    verify = true;
                }
            }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return verify;
    }

    @Override
    public void initialize(NotEmptyIfParamIs constraintAnnotation) {
        this.targetElement = constraintAnnotation.targetElement();
        this.moniteElement = constraintAnnotation.moniteElement();
        this.elementValue = constraintAnnotation.elementValue();
    }






}
